package java_thinking.unit_14._14_3;


import java_thinking.net.mindview.util.MapData;
import java_thinking.unit_14.pets.Pet;

import java.util.LinkedHashMap;
import java.util.Map;

import static java_thinking.net.mindview.util.Print.printnb;

/**
 * @Description : 使用动态的instanceof
 * @author: cww
 * @DateTime: 2019/3/29 8:49
 */

public class PetCount3 {
    static class PetCounter extends LinkedHashMap<Class<? extends Pet>,Integer> {
        public PetCounter () {
            /**
             * 为了对所有不同类型的Pet进行计数，这里预加载了LiteralPetCreator.allTypes中的类型，并且初始化为0
             */
            super(MapData.map(LiteralPetCreator.allTypes,0));
        }

        /**
         * entry.getValue()初始是0是上面super初始化的
         * @param pet
         */
        public void count (Pet pet) {
            for (Map.Entry<Class<? extends Pet>,Integer> entry : entrySet()){
                if (entry.getKey().isInstance(pet))
                    put(entry.getKey(),entry.getValue()+1);
            }
        }
        @Override
        public String toString() {
            StringBuilder result = new StringBuilder("{");
            for (Map.Entry<Class<? extends Pet>,Integer> entry:entrySet()){
                result.append(entry.getKey().getSimpleName());
                result.append("=");
                result.append(entry.getValue());
                result.append(", ");
            }
            result.delete(result.length()-2,result.length());
            result.append("}");
            return result.toString();
        }

        public static void main(String[] args) {
            PetCounter petCounter = new PetCounter();
            for (Pet pet:Pets.createArray(20)){
                printnb(pet.getClass().getSimpleName()+" ");
                petCounter.count(pet);
            }
            System.out.println();
            System.out.println(petCounter);
        }
    }
}
